package vn.edu.ptithcm.pim.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Customer;
import vn.edu.ptithcm.pim.service.CityService;
import vn.edu.ptithcm.pim.service.CustomerService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.FileUtil;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class HandleCustomerController extends SimpleFormController {

	private CustomerService customerService;
	private UserService userService;
	private CityService cityService;

	Logger log = Logger.getLogger(HandleCustomerController.class);

	public HandleCustomerController() {
		super();
		setSessionForm(true);
		setCommandName("customer");
		setCommandClass(Customer.class);
		setFormView(UrlConstants.HANDLE_CUSTOMER_URL);
		setSuccessView(UrlConstants.HANDLE_CUSTOMER_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Customer customer = null;
		int id = ParamUtil.getInteger(request, "id", 0);
		customer = customerService.findById(new Long(id));
		if (customer == null) {
			customer = new Customer();
		}
		return customer;
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		if (request instanceof MultipartHttpServletRequest) {
			binder.registerCustomEditor(String.class,
					new StringMultipartFileEditor());
		}
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Customer informCustomer = (Customer) command;
		String cmd = ParamUtil.getString(request, Constants.CMD, "");
		String logourl = FileUtil.transferTo(request, "logourl",
				Constants.UPLOADED_FILE_FOLDER);
		if (!logourl.isEmpty()) {
			informCustomer.setLogourl(logourl);
		} else if (Constants.EDIT.equals(cmd)) {
			long id = informCustomer.getCustomerid();
			Customer inDBCustomer = customerService.findById(id);
			if (inDBCustomer != null) {
				informCustomer.setLogourl(inDBCustomer.getLogourl());
			}
		}

		if (Constants.EDIT.equals(cmd)) {
			customerService.saveOrUpdate(informCustomer);
			request.setAttribute("editOK", true);
			log.debug("edited");

		} else if (Constants.ADD.equals(cmd)) {
			customerService.save(informCustomer);
			request.setAttribute("addOK", true);
			log.debug("added");
		}

		return showForm(request, response, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		if (userService.isSignedIn(request)) {
			Map<String, Object> bean = new HashMap<String, Object>();
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			bean.put("cities", cityService.getAll());

			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			bean.put(Constants.CMD, cmd);

			String returnToFullPageURL = ParamUtil.getString(request,
					Constants.RETURN_TO_FULL_PAGE_URL, "");

			if (returnToFullPageURL.isEmpty()) {
				returnToFullPageURL = request.getHeader("referer");
			}
			bean.put(Constants.RETURN_TO_FULL_PAGE_URL, returnToFullPageURL);

			request.setAttribute("bean", bean);
		} else {
			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			String redirectLink = "";
			if (Constants.ADD.equals(cmd)) {
				redirectLink = UrlConstants.HANDLE_CUSTOMER_URL
						+ UrlConstants.HTM;
			} else if (Constants.EDIT.equals(cmd)) {
				int id = ParamUtil.getInteger(request, "id", 0);
				redirectLink = UrlConstants.HANDLE_CUSTOMER_URL
						+ UrlConstants.HTM + "?id=" + id;
			}
			log.info("HandleCustomerController || redirectLink : "
					+ redirectLink);
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public CityService getCityService() {
		return cityService;
	}

	public void setCityService(CityService cityService) {
		this.cityService = cityService;
	}

}
